package com.sq.partner.manager.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.service.TradConfigService;
import com.sq.partner.manager.util.*;
import org.apache.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.IGatewayAgentInfoMtDao;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradSaleAgent;
import com.sq.partner.manager.service.IGatewayAgentInfoMtService;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.INlifePlanConfigService;
import com.sq.partner.manager.service.JSCDService;

import org.springframework.web.bind.annotation.RequestMethod;
/**
 *
 */
@Controller
@RequestMapping(value = "/extend")
public class JSCDController {
	private static Logger logger = LogUtil.getLog(JSCDController.class);
	@Resource
	IGatewayInsureService gatewayInsureService;
	@Resource
	private INlifePlanConfigService nlifePlanConfigService;
	@Resource
	private IGatewayAgentInfoMtService agentInfoMtService;
	@Resource
	private IGatewayAgentInfoMtDao agentInfoMtDao;
	@Resource
	private JSCDService  JSCDService;
	@Resource
	private TradConfigService tradConfigService;
	@RequestMapping(value = "/jscdconfig")
	public String saveAgentInfo(HttpServletRequest request,String data,ModelMap modeMap) throws Exception {
		TradAgentInfo tinfo=changeDate(data);
		if(tinfo==null){
			return "extend/err";
		}
		TradAgentInfo info = new TradAgentInfo();//此对象用于页面回显信息
		info.setDptCde(tinfo.getDptCde());
		info.setKey1(tinfo.getKey1());
		info.setKey2(tinfo.getKey2());
		info.setKey3(tinfo.getKey3());
		info.setKey4(tinfo.getKey4());
		info.setKey5(tinfo.getKey5());
		info.setChannelCode(tinfo.getChannelCode());

		//页面初始化加载“代理类型”列表
		List<DictDto> agentTypeList = DictCache.getDict("agent_type");

		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		newBSList = DictCache.remakeNewBussinessSource();
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		modeMap.put("newBSList", newBSList);
		modeMap.put("oldBSList", oldBSList);
		modeMap.put("btcList", btcList);
		modeMap.put("channelList", channelList);
		modeMap.put("info", info);
		modeMap.put("agentTypeList", agentTypeList);
		return "extend/jscdconfig";
	}
	/***
	 * 传入参数处理
	 */
	private TradAgentInfo changeDate(String data){
		TradAgentInfo info=new TradAgentInfo();
		logger.info("接口传入数据"+data);
		if(StrUtil.isEmpty(data)){
			return null;
		}
		String channelDate=EncryptUtil.base64Decode(data);
		logger.info("解码后： "+channelDate);
		String infoDate=EncryptUtil.decrypt(channelDate);
		logger.info("解密后："+infoDate);
		Map<String,String> map=JsonUtils.parseJson(infoDate, Map.class);
		/**用户名密码验证*/
		try {
			String user=Config.getProp("jscd.user");
			String pwd=Config.getProp("jscd.pwd");
			if(user.equals(map.get("USER"))&&pwd.equals(map.get("PWD"))){
				logger.info("用户名密码验证成功配置的用户名密码为"+user+"----"+pwd);
				/**封装参数*/
				/**合作伙伴代码*/
				info.setChannelCode(map.get("CHANNEL_CODE"));
				/**归属渠道*/
				info.setChannleCode(map.get("CHANNLE_CODE"));
				/**渠道类型**/
				info.setChannleType(map.get("CHANNLE_TYPE"));
				/**新业务来源**/
				info.setNewBsnsType(map.get("NEW_BSNS_TYPE"));
				/**原业务员来源*/
				info.setCategoryCode(map.get("CATEGORY_CODE"));
				/**出单机构*/
				info.setDptCde(map.get("DPT_CDE"));
				/**业务员代码*/
				info.setEmpNo(map.get("EMP_NO"));
				/**业务员名称*/
				info.setEmpName(map.get("EMP_NAME"));
				/**团队代码*/
				info.setTeamCode(map.get("TEAM_CODE"));
				/**团队名称*/
				info.setTeamName(map.get("TEAM_NAME"));
				/**代理人编码*/
				info.setAgentNo(map.get("AGENT_NO"));
				/**代理人协议号**/
				info.setProtocolNo(map.get("PROTOCOL_NO"));
				/**代理人名称*/
				info.setCbrkrname(map.get("C_BRKR_NME"));
				/**服务代码*/
				info.setServiceCode(map.get("SERVICE_CODE"));
				/**服务名称*/
				info.setServiceName(map.get("SERVICE_NAME"));
				/**k1 k2 k3 k4 k5**/
				info.setKey1(map.get("KEY1"));
				info.setKey2(map.get("KEY2"));
				info.setKey3(map.get("KEY3"));
				info.setKey4(map.get("KEY4"));
				info.setKey5(map.get("KEY5"));
				info.setProductType(map.get("PRODUCT_TYPE"));
			}else{
				logger.info("用户名密码验证失败配置的用户名密码为"+user+"----"+pwd);
				return null;
			}
		} catch (Exception e) {
			logger.info("数据转换错误",e);
		}
		return info;
	}
	@RequestMapping(value="/changeTypeId")
	@ResponseBody
	public Map<String,Object> changeType(String channelCode,String key1,String key2,String key3,String key4,String key5,String productType) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("channelCode", channelCode);
		map.put("key1", key1);
		map.put("key2", key2);
		map.put("key3", key3);
		map.put("key4", key4);
		map.put("key5", key5);
		/**车意联合*/
		map.put("unionType", "CYLH");
		map.put("productType", productType);
		List<TradAgentInfo> list=agentInfoMtDao.queryAgentInByMap(map);
		Map<String,Object> map1= new HashMap<String,Object>();
		if(list.size()>0&&list!=null){
			map1.put("ishave", true);
			map1.put("agentInfoId", list.get(0).getId());
			map1.put("info",list.get(0));
			map1.put("result",true);
		} else{
			map1.put("agentInfoId", "");
			map1.put("ishave", false);
			map1.put("result",false);
		}
		return map1;
	}
	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 */
	@RequestMapping(value = "/loadCoreDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(Integer size,Integer pageIndex,String deptCode,String deptCNname,String channelCode) throws Exception{
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode+"%");
		dept.setDeptCname(deptCNname);
		page.setType(dept);
		Page<CoreDept> page2=gatewayInsureService.queryPageForCoreDeptJSCD(page,channelCode);
		return page2;
	}
	/**
	 * 查询业务员-团队信息(从销管获取)
	 * @param COMCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querySauserAndTeamInfo")
	@ResponseBody
	public Result querySauserAndTeamInfo(String COMCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)){
			return Result.error("出单机构不能为空");
		}
		try{
			return nlifePlanConfigService.querySauserAndTeamInfo(COMCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
	}


	//选取旧业务来源
	@RequestMapping(value = "/chooseBsnsType")
	public @ResponseBody DictDto chooseBsnsType(String parentCode,String newBsnsCode) throws Exception {
		DictDto dd = new DictDto();
		if (StrUtil.isNotEmpty(parentCode)&&StrUtil.isNotEmpty(newBsnsCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode("new_business_source", parentCode);
			for (DictDto dictDto : subDataList) {
				if(newBsnsCode.equals(dictDto.getCode())){
					return dictDto;
				}
			}
		}else{
			dd.setOtherCode("");
		}
		return dd;
	}

	// 归属渠道-渠道类型-新业务来源处理
	@RequestMapping(value = "/loadSubDropList")
	public @ResponseBody List<DictDto> getSubDropListData(String codeType, String parentCode) throws Exception {
		List<DictDto> list = new ArrayList<DictDto>();
		if (StrUtil.isNotEmpty(codeType) && StrUtil.isNotEmpty(parentCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType, parentCode);
			//复制list
			list.addAll(subDataList);
			//倒序
			Collections.reverse(list);
			DictDto dd = new DictDto();
			dd.setCode("");
			dd.setCodeName("----请选择----");
			list.add(dd);
			//倒序
			Collections.reverse(list);
			return list;
		}else{
			DictDto dd = new DictDto();
			dd.setCode("");
			if("channel_type".equals(codeType)){
				dd.setCodeName("----请选择归属渠道----");
			}else if("new_business_source".equals(codeType)){
				dd.setCodeName("----请选择渠道类型----");
			}
			list.add(dd);
		}
		return list;
	}

	@RequestMapping(value = "/saveAgentMtInfo", method = RequestMethod.POST)
	@ResponseBody
	public Result saveAgentMtInfo(HttpSession session,TradAgentInfo agentMtInfo,String saleArry,String prodSet,String realChannel) throws Exception {
		if(StrUtil.isEmpty(agentMtInfo.getChannelCode())){
			return Result.error("合作伙伴不能为空");
		}else if(StrUtil.isEmpty(agentMtInfo.getDptCde())){
			return Result.error("出单机构不能为空");
		}else if(StrUtil.isEmpty(agentMtInfo.getChannleCode())){
			return Result.error("请选择归属渠道");
		}else if(StrUtil.isEmpty(agentMtInfo.getChannleType())){
			return Result.error("请选择渠道类型");
		}else if(StrUtil.isEmpty(agentMtInfo.getNewBsnsType())){
			return Result.error("请选择新业务来源");
		}else if(StrUtil.isEmpty(agentMtInfo.getCategoryCode())){
			return Result.error("请选择原业务来源");
		}
		if("19002".equals(agentMtInfo.getCategoryCode())||"19003".equals(agentMtInfo.getCategoryCode())){
			if(StrUtil.isEmpty(agentMtInfo.getAgentNo())){
				return Result.error("请输入代理人代码");
			}
			if(StrUtil.isEmpty(agentMtInfo.getProtocolNo())){
				return Result.error("请输入代理协议号");
			}
		}
		if(StrUtil.isEmpty(agentMtInfo.getServiceCode())){
			return Result.error("服务代码 不能为空");
		}else if(StrUtil.isEmpty(agentMtInfo.getEmpNo())){
			return Result.error("业务员代码不能为空");
		}else if(StrUtil.isEmpty(agentMtInfo.getTeamCode())){
			return Result.error("团队代码不能为空");
		}else if(StrUtil.isEmpty(agentMtInfo.getTeamName())){
			return Result.error("团队名称不能为空");
		}else if(StrUtil.isEmpty(agentMtInfo.getProductType())) {
			return Result.error("销售落地数据对应的产品类型不能为空");
		}
		if(!"G".equals(realChannel) && !"K".equals(realChannel)){
		//校验销售渠道信息是否有效
		List<DictDto> newBusinessSource = DictCache.getDict("new_business_source");
		if(DictCache.statusCheck("new_business_source", agentMtInfo.getNewBsnsType()) == false){
			return Result.error("此业务来源:"+agentMtInfo.getNewBsnsType()+  "已停用，请核实修改。");
		}
		Map<String,Object> map = new HashMap<String, Object>();
		SimpleDateFormat dateformat = new SimpleDateFormat("0000yyyyMMddHHmmss");
		String SERIALDECIMAL = dateformat.format(System.currentTimeMillis());
		String AGENTTYPE = getAgentTypeByNewBsnsType(agentMtInfo.getNewBsnsType(),newBusinessSource);
		String CHANNELNAME = agentMtInfo.getChannleType().substring(0,1);
		List<String> PRODCODEList = Arrays.asList(prodSet.split(","));
		map.put("prodList",PRODCODEList);
		map.put("SERIALDECIMAL",SERIALDECIMAL);
		map.put("COMCODE",agentMtInfo.getDptCde());  //机构代码
		map.put("BUSINESSSOURCE",agentMtInfo.getNewBsnsType()); //业务来源
		map.put("CHANNELNAME",CHANNELNAME); //渠道类型
		map.put("AGENTTYPE",AGENTTYPE); //代理类型
		map.put("USERCODE",agentMtInfo.getEmpNo()); //业务员代码
		map.put("TEAMCODE",agentMtInfo.getTeamCode()); //团队代码
		map.put("AGENTCODE",agentMtInfo.getAgentNo()); //中介代码
		map.put("AGREEMENTNO",agentMtInfo.getProtocolNo()); //协议代码
		map.put("PERMITNOB",agentMtInfo.getcAgentSlsCde()); //代理人职业证号
		map.put("SERVICECODE",agentMtInfo.getServiceCode()); //服务代码
		String xml="";
		String responseXml="";
		xml= FreeMarkerUtil.process("/saleChannelInfo.ftl", map);
		logger.info("请求30005接口的报文:"+xml);
		responseXml = HttpConnectorUtil.interaction(Config.getProp("salemanage.check.url"),xml,agentMtInfo.getChannelCode(),Constants.GW_CH_TX_30005);
		logger.info("销管校验返回报文"+responseXml);
		Document doucument = DocumentHelper.parseText(responseXml);
		Element element = doucument.getRootElement();
		///解析报文校验查询是否成功
		String resultCode = JSCDService.selectSingleNodeByRoot(element , "/XML/HEAD/RESMSGCODE");
		if ("".equals(resultCode) || resultCode.length() != 4 || (!"0000".equals(resultCode) && !"0001".equals(resultCode))){
			String errorInfo = element.selectSingleNode("/INSUREQRET/HEAD/RESULTCODE") == null ? "系统错误 请联系管理员" : element.selectSingleNode("/INSUREQRET/HEAD/RESULTCODE").getText();
			throw new AppException(errorInfo);
		}
		if("0001".equals(resultCode)){
			String SALESMSG = JSCDService.selectSingleNodeByRoot(element , "/XML/BODY/SALESMSG");
			String AGENTMSG = JSCDService.selectSingleNodeByRoot(element , "/XML/BODY/AGENTMSG");
			String AGREEMENTMSG = JSCDService.selectSingleNodeByRoot(element , "/XML/BODY/AGREEMENTMSG");
			String SERVICECODEMSG = JSCDService.selectSingleNodeByRoot(element , "/XML/BODY/SERVICECODEMSG");
			String AGENTSALESMSG = JSCDService.selectSingleNodeByRoot(element , "/XML/BODY/AGENTSALESMSG");
			String errorMsg = SALESMSG + AGENTMSG + AGREEMENTMSG + SERVICECODEMSG +AGENTSALESMSG;
			return Result.error("销管校验异常："+"<br>"+errorMsg);
		}
		}
		try {
			agentMtInfo.setUnionType("CYLH");
			return JSCDService.saveAgentMtInfo(agentMtInfo,saleArry,prodSet);
		} catch (Exception e) {
			logger.info("操作失败",e);
			return Result.error("操作失败");
		}
	}
	/**
	 * 查询服务代码信息(从销管获取)
	 * @param COMCODE
	 * @param BUSINESSSOURCE
	 * @param CHANNELNAME
	 * @param USERCODE
	 * @param AGENTCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryServiceNo")
	@ResponseBody
	public Result queryServiceNo(String COMCODE,String BUSINESSSOURCE,
								 String CHANNELNAME,String USERCODE,String AGENTCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)) return Result.error("出单机构不能为空");
		if(StrUtil.isEmpty(BUSINESSSOURCE)) return Result.error("业务来源不能为空");
		if(StrUtil.isEmpty(CHANNELNAME)) return Result.error("渠道名称不能为空");
		if(StrUtil.isEmpty(USERCODE)) return Result.error("业务员代码不能为空");

		Result result = null;
		try{
			result = nlifePlanConfigService.queryServiceNo(COMCODE, BUSINESSSOURCE, CHANNELNAME, USERCODE, AGENTCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}
	/**
	 * 查询中介-协议信息(从销管获取)
	 * @param COMCODE
	 * @param TEAMCODE
	 * @param BUSINESSSOURCE
	 * @param CHANNELNAME
	 * @param PRODCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentAndAgreeInfo")
	@ResponseBody
	public Result queryAgentAndAgreeInfo(String COMCODE,String TEAMCODE,
										 String BUSINESSSOURCE,String CHANNELNAME,String PRODCODE,String productType,String empNo,String agentCode) throws Exception {
		if(StrUtil.isEmpty(COMCODE)) return Result.error("出单机构不能为空");
		if(StrUtil.isEmpty(TEAMCODE)) return Result.error("团队代码不能为空");
		if(StrUtil.isEmpty(BUSINESSSOURCE)) return Result.error("业务来源不能为空");
		if(StrUtil.isEmpty(CHANNELNAME)) return Result.error("渠道名称不能为空");
		//if(StrUtil.isEmpty(PRODCODE)) return Result.error("产品代码不能为空");
		if(StrUtil.isEmpty(productType)) return Result.error("产品类型不能为空");

		Result result = null;
		Map<String,String> dptCdeAndType = new HashMap<String, String>();
		try{
			dptCdeAndType.put("dptCde",COMCODE.substring(0,2));
			dptCdeAndType.put("planType",productType);
			List<String> PRODCODEList = tradConfigService.selectCoreProdCodeByDptCde(dptCdeAndType);
			if (PRODCODEList.size() == 0 || PRODCODEList == null){
				return Result.error("合作伙伴系统未维护此产品类型的车+X关联信息配置");
			}
			StringBuilder ProCodeStr = new StringBuilder();
			for (int i = 0; i < PRODCODEList.size(); i++) {
				ProCodeStr.append(PRODCODEList.get(i));
				if (i != (PRODCODEList.size() - 1)) {
					ProCodeStr.append(",");
				}
			}
			logger.info(ProCodeStr);
			result = JSCDService.queryAgentAndAgreeInfo(COMCODE, TEAMCODE, BUSINESSSOURCE, CHANNELNAME, ProCodeStr.toString(),empNo,agentCode);
			//result = nlifePlanConfigService.queryAgentAndAgreeInfo(COMCODE, TEAMCODE, BUSINESSSOURCE, CHANNELNAME, ProCodeStr.toString());
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}
	/**
	 * 加载广东销售信息
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadSale")
	@ResponseBody
	public Map<String,Object> loadSale(String id) throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		try {
			/**销售人员字典*/
			List<DictDto> saleMenTypes=DictCache.getDict(Constants.DICT_SALE_MEN_TYPE);
			List<DictDto> saleTypes=DictCache.getDict(Constants.DICT_SALES_TYPE);
			List<DictDto> roleTypes=DictCache.getDict(Constants.DICT_ROLE_STYPE);/**新意健险销售人员类别*/
			List<TradSaleAgent> saleAgents=null;
			if(StrUtil.isNotEmpty(id)){
				saleAgents=agentInfoMtService.queryTrandSaleAgent(id);
			}
			map.put("saleMenTypes", saleMenTypes);
			map.put("saleTypes", saleTypes);
			map.put("saleAgents", saleAgents);
			map.put("roleTypes", roleTypes);
			map.put("success", true);
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}

	/***
	 * 销售信息保存
	 */
	@RequestMapping(value = "/addTradSaleAgent")
	@ResponseBody
	public Result addTradSaleAgent(String id,String saleArry) throws Exception {
		Result result = null;
		if(StrUtil.isNotEmpty(id)){
			Map<String, String> map=new HashMap<String, String>();
			map.put("id", id);
			/*	tradPlanSaleService.deleteTrade(map);*/
			agentInfoMtService.deleteTrade(id);
			List<Map<String,String>> list = JsonUtils.parseJson(saleArry, ArrayList.class);
			List<TradSaleAgent> planSales=new ArrayList<TradSaleAgent>();
			for (Map<String, String> map2 : list) {
				TradSaleAgent planSale=new TradSaleAgent();
				planSale.setAgentFee((Double.parseDouble(map2.get("agentFee"))+""));
				planSale.setAgentNo(map2.get("agentNo"));
				planSale.setEmpNo(map2.get("empNo"));
				planSale.setPersonType(map2.get("personType"));
				planSale.setPracticeNo(map2.get("practiceNo"));
				planSale.setSalePerson(map2.get("salePerson"));
				planSale.setSaleType(map2.get("saleType"));
				planSale.setSeqNo(map2.get("seqNo"));
				planSale.setPlanType(map2.get("planType"));
				planSale.setAgentCode(map2.get("agentCode"));
				planSale.setAgentName(map2.get("agentName"));
				planSale.setSaleName(map2.get("saleName"));
				planSale.setId(Long.parseLong(id));
				planSale.setInsertDate(new Date());
				planSales.add(planSale);
			}
			Boolean flag=agentInfoMtService.addTrade(planSales);
			if(flag){
				result=Result.success("添加成功");
			}else{
				result=Result.error("添加失败");
			}
		}else{
			result=Result.error("代理信息ID为空");
		}
		return result;
	}



	private String getAgentTypeByNewBsnsType(String newBsnsType,List<DictDto> newBusinessSource) {
		String agentType = "";
		for (DictDto dictDto : newBusinessSource) {
			if (newBsnsType.equals(dictDto.getCode())){
				if ("1900101".equals(dictDto.getOtherCode2())){
					agentType = "0";
					break;
				}else if ("1900203".equals(dictDto.getOtherCode2())) {
					agentType = "1";
					break;
				}else if ("1900201".equals(dictDto.getOtherCode2())) {
					agentType = "2";
					break;
				}else if ("1900202".equals(dictDto.getOtherCode2())) {
					agentType = "3";
					break;
				}else if ("1900301".equals(dictDto.getOtherCode2())) {
					agentType = "4";
					break;
				}
			}
		}
		return agentType;
	}

	@RequestMapping(value = "/deleteAgentMtInfoById")
	@ResponseBody
	public Result addTradSaleAgent(Long id) throws Exception {
		TradAgentInfo tradAgentInfo = new TradAgentInfo();
		Result result = null;
		tradAgentInfo.setId(id);
		try{
			agentInfoMtService.deleteTradAgentInfoRela(id+"");
			agentInfoMtService.deleteAgentMtInfo(tradAgentInfo);
			return Result.success("删除成功！");
		}catch (Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}

	}

	//查询未授权的产品
	@RequestMapping(value = "/queryUnauthorizedProducts")
	@ResponseBody
	public Result queryUnauthorizedProducts(String COMCODE, String productType,  String TEAMCODE,
											String BUSINESSSOURCE, String CHANNELNAME, String PRODCODE,String empNo,String agentCode) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, String> dptCdeAndType = new HashMap<String, String>();
		dptCdeAndType.put("dptCde", COMCODE.substring(0, 2));
		dptCdeAndType.put("planType", productType);
		//从数据库中查到的产品
		List<String> PRODCODEList = tradConfigService.selectCoreProdCodeByDptCde(dptCdeAndType);
		StringBuilder ProCodeStr = new StringBuilder();
		for (int i = 0; i < PRODCODEList.size(); i++) {
			ProCodeStr.append(PRODCODEList.get(i));
			if (i != (PRODCODEList.size() - 1)) {
				ProCodeStr.append(",");
			}
		}
		List<Map<String,Object>>  AGENTAGREEMENTList =(List<Map<String,Object>>) JSCDService.queryAgentAndAgreeInfo(COMCODE,TEAMCODE,BUSINESSSOURCE,CHANNELNAME,ProCodeStr.toString(),empNo,agentCode).getData();
		logger.info("销管返回的信息:"+ AGENTAGREEMENTList);
		//销管授权的产品
		Set<String>  prodset = (Set<String>)AGENTAGREEMENTList.get(0).get("prodSet");
		logger.info("从返回报文取出的授权产品号:"+ prodset);
		List<String> prodlist = new ArrayList<String>();
		prodlist.addAll(prodset);
		logger.info("数据库查询到的产品:"+ PRODCODEList);
		logger.info("销管授权的产品"+ prodlist);
		//未授权产品集合
		PRODCODEList.removeAll(prodlist);
		logger.info("执行差集后的产品"+ PRODCODEList);
		resultMap.put("prodlist",prodlist);
		resultMap.put("PRODCODEList",PRODCODEList);
		try {
			return Result.success(resultMap);
		} catch (Exception e) {
			logger.info(e);
			return Result.error(e.getMessage());
		}
	}

	@RequestMapping(value = "/recallAgentInfo")
	public String   recallAgentInfo(String key1,String key2,String key3,String key4,String key5,String productType,String channelCode,ModelMap modeMap) throws Exception {
		TradAgentInfo tradAgentInfo= new TradAgentInfo();
		tradAgentInfo.setKey1(key1);
		tradAgentInfo.setKey2(key2);
		tradAgentInfo.setKey3(key3);
		tradAgentInfo.setKey4(key4);
		tradAgentInfo.setKey5(key5);
		tradAgentInfo.setProductType(productType);
		tradAgentInfo.setChannelCode(channelCode);
		if(tradAgentInfo==null){
			return "extend/err";
		}
		//查询key1---key5是否已经存在
		Map<String, String> map = new HashMap<String, String>();
		map.put("channelCode", tradAgentInfo.getChannelCode());
		map.put("key1", tradAgentInfo.getKey1());
		map.put("key2", tradAgentInfo.getKey2());
		map.put("key3", tradAgentInfo.getKey3());
		map.put("key4", tradAgentInfo.getKey4());
		map.put("key5", tradAgentInfo.getKey5());
		/**车意联合*/
		map.put("unionType", "CYLH");
		map.put("productType",tradAgentInfo.getProductType());
		List<TradAgentInfo> list=agentInfoMtDao.queryAgentInByMap(map);
		if(list!=null&&list.size()>0){
			logger.info("已存在，加载合作伙伴渠道信息");
			tradAgentInfo=list.get(0);
			modeMap.put("ishave", true);
		}
		//页面初始化加载“代理类型”列表
		List<DictDto> agentTypeList = DictCache.getDict("agent_type");

		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		newBSList = DictCache.remakeNewBussinessSource();
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		modeMap.put("newBSList", newBSList);
		modeMap.put("oldBSList", oldBSList);
		modeMap.put("btcList", btcList);
		modeMap.put("channelList", channelList);
		modeMap.put("info", tradAgentInfo);
		modeMap.put("agentTypeList", agentTypeList);
		return "extend/jscdconfig";
	}

	//查询广东销售员信息
	@RequestMapping(value = "/querySalesInfo")
	@ResponseBody
	public Result querySalesInfo(String COMCODE, String USERNAME,  String TEAMCODE,String USERCODE) throws Exception {
		Map<String,String> map = JSCDService.querySalesInfo(COMCODE,USERNAME,TEAMCODE,USERCODE);
		try {
			if(map.isEmpty()){
				return Result.error("未查询到销售员信息！");
			}
			return Result.success(map);
		} catch (Exception e) {
			logger.info(e);
			return Result.error(e.getMessage());
		}
	}

	//根据页面选择的产品类型和5个key查询销售信息
	@RequestMapping(value = "/queryAgentInfoByProdType")
	@ResponseBody
	public Map<String,Object> queryAgentInfoByProdType(String key1,String key2,String key3,String key4,String key5,
	String productType,String channelCode) throws Exception {
		Map<String,Object> map = new HashMap<String, Object>();
		Map<String,String> queryMap = new HashMap<String, String>();
		queryMap.put("channelCode", channelCode);
		queryMap.put("key1", key1);
		queryMap.put("key2", key2);
		queryMap.put("key3", key3);
		queryMap.put("key4", key4);
		queryMap.put("key5",key5);
		/**车意联合*/
		queryMap.put("unionType", "CYLH");
		queryMap.put("productType",productType);
		List<TradAgentInfo> list = agentInfoMtDao.queryAgentInByMap(queryMap);
		TradAgentInfo tradAgentInfo = new TradAgentInfo();
		map.put("prodType", productType);
		if(list!=null&&list.size()>0){
			logger.info("已存在，加载合作伙伴渠道信息");
			tradAgentInfo=list.get(0);
			map.put("ishave", true);
			map.put("info",tradAgentInfo);
		}
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		map.put("newBSList",newBSList);
		map.put("channelList",channelList);
		return map;
	}
}
